import subprocess
import requests
import time
import re
from datetime import date
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from login import Lighthouse
from openpyxl import Workbook
from selenium import webdriver

log_filename = '错误报告{}.log'.format(time.strftime('%Y-%m-%d %H%M%S'))
date_format = '%Y-%m-%d'


def log_error(line):
    with open(log_filename, 'a', encoding='utf-8') as f:
        f.write(line + "\r\n")


def get_date_from_timestamp(timestamp):
    return time.strftime(date_format, time.localtime(timestamp))


def get_datetime_from_timestamp(timestamp):
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))


def set_cookies(session, cookie_dict):
    for name, value in cookie_dict.items():
        session.cookies.set(name, value)


def requests_retry_session(
    retries=3,
    backoff_factor=0.3,
    status_forcelist=(500, 502, 504),
    session=None,
):
    session = session or requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    session.headers.update({"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                                          "(KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"})
    return session


def show_image(filename):
    subprocess.call([filename], shell=True)


class WeChatClient:
    def __init__(self, login_service, url='https://mp.weixin.qq.com'):
        """
        通过灯塔登录接口获取公众号后台资料
        :param Lighthouse login_service:
        """
        self.url = url
        self.login = login_service
        self.session = requests_retry_session()
        self.gh_id = None
        self.gh_nickname = '?'
        self.token = None
        self.index_url = None
        self.index_response = None
        self.driver = webdriver.Chrome('C:\\chromedriver\\chromedriver.exe')

    def log_line(self, msg, gh_nickname=None, gh_id=None):
        line = '[{}]({}) {}'.format(gh_nickname if gh_nickname else self.gh_nickname,
                                    gh_id if gh_id else self.gh_id, msg)
        print(line)
        return line

    def log_err(self, err, gh_nickname=None, gh_id=None):
        log_error(self.log_line(err, gh_nickname, gh_id))

    def enter(self, gh_id, gh_nickname=None):
        cookies = self.login.get_wx_cookie(gh_id)
        if cookies:
            self.log_line('获取Cookie成功', gh_nickname, gh_id)
            set_cookies(self.session, cookies)
            response = self.session.get(url=self.url, verify=False)
            self.index_url = str(response.url)
            try:
                token = re.findall('token=(\\d+)', self.index_url)[0]
            except IndexError:
                self.log_err('微信后台登录失败，检查Cookie是否有效', gh_nickname, gh_id)
                return False
            self.gh_id = gh_id
            self.gh_nickname = gh_nickname
            self.token = token
            self.index_response = response.content.decode('utf-8')
            self.log_line('后台登录成功，Token={}'.format(token))
            return cookies
        else:
            self.log_err('一键登录状态异常，跳过', gh_nickname, gh_id)
            return False


def make_workbook(sheet_name=None):
    workbook = Workbook()
    sheet = workbook.active
    if sheet_name:
        sheet.title = sheet_name
    return workbook, sheet


def get_today():
    return date.today().strftime(date_format)
